﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.Core.Service.Customer;
using WaterRevenueMS.Core.Service.BasicSet;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Domain.ViewModels.Customer.MeterInfo;
using WaterRevenueMS.Domain.ViewModels.BasicSet.KindOfWaterUse;
using WaterRevenueMS.Domain.ViewModels.BasicSet.RelayType;
using WaterRevenueMS.Domain.ViewModels.BasicSet.ConcentratorType;
using WaterRevenueMS.Domain.ViewModels.BasicSet.HandSetType;
using WaterRevenueMS.Componnent.Common;
using System.Linq.Expressions;
using WaterRevenueMS.Componnent.Entities.Customer;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Domain.ViewModels.BasicSet.WayOfCharge;
using WaterRevenueMS.Domain.ViewModels.BasicSet.MeterType;
using WaterRevenueMS.Domain.ViewModels.BasicSet.WaterCaliber;
using WaterRevenueMS.Domain.ViewModels.BasicSet.Manufacturer;
using WaterRevenueMS.Core.Service.BaseData;
using WaterRevenueMS.Domain.ViewModels.BaseData.MeterBook;
using WaterRevenueMS.Domain.ViewModels.Customer.Customer;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using WaterRevenueMS.WebUI.Models;
using System.Web.UI;

namespace WaterRevenueMS.WebUI.Controllers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MeterInfoController : AdminController
    {
        [Import]
        public IMeterInfoService MeterInfoService { get; set; }

        [Import]
        private ICustomerService CustomerService { get; set; }

        [Import]
        private IWayOfChargeService WayOfChargeService { get; set; }

        [Import]
        private IKindOfWaterUseService KindOfWaterUserService { get; set; }

        [Import]
        private IMeterTypeService MeterTypeService { get; set; }

        [Import]
        private IRelayTypeService RelayTypeService { get; set; }

        [Import]
        private IConcentratorTypeService ConcentratorTypeService { get; set; }

        [Import]
        private IHandSetTypeService HandSetTypeService { get; set; }

        [Import]
        private IWaterCaliberService WaterCaliberService { get; set; }

        [Import]
        private IManufacturerService ManufacturerService { get; set; }

        [Import]
        private IMeterBookService MeterBookService { get; set; }

        [Import]
        private IRuleOfCodeService RuleOfCodeService { get; set; }

        [AdminLayout]
        public ActionResult Index()
        {
            var model = new MeterInfoModel();
            var KindOfWaterUseDatas = KindOfWaterUserService.KindOfWaterUses.Where(t => t.IsDeleted == false)
                .Select(t=>new KindOfWaterUseModel { 
                    Id=t.Id,
                    Yong_SXZ=t.Yong_SXZ
                });
            foreach (var item in KindOfWaterUseDatas)
            {
                model.Search.KindOfWaterUseItems.Add(new SelectListItem {Text=item.Yong_SXZ,Value=item.Id.ToString() });
            }
            var RelayTypeDatas = RelayTypeService.RelayTypes.Where(t => t.IsDeleted == false)
                .Select(t => new RelayTypeModel { 
                    Id=t.Id,
                    Zhong_JLX=t.Zhong_JLX
                });
            foreach (var item in RelayTypeDatas)
            {
                model.Search.RelayTypeItems.Add(new SelectListItem {Text=item.Zhong_JLX,Value=item.Id.ToString() });
            }
            var ConcentratorTypeDatas = ConcentratorTypeService.ConcentratorTypes.Where(t => t.IsDeleted == false)
                .Select(t => new ConcentratorTypeModel { 
                    Id=t.Id,
                    Ji_ZQLX=t.Ji_ZQLX
                });
            foreach (var item in ConcentratorTypeDatas)
            {
                model.Search.ConcentratorTypeItems.Add(new SelectListItem {Text=item.Ji_ZQLX,Value=item.Id.ToString() });
            }
            var HandSetDatas = HandSetTypeService.HandSetTypes.Where(t => t.IsDeleted == false)
                .Select(t=>new HandSetTypeModel { 
                    Id=t.Id,
                    Shou_CQLX=t.Shou_CQLX
                });
            foreach (var item in HandSetDatas)
            {
                model.Search.HandSetItems.Add(new SelectListItem {Text=item.Shou_CQLX,Value=item.Id.ToString() });
            }
            return View(model);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = MeterInfoService.MeterInfos.Count(t => t.IsDeleted == false);

            var expr = BuildSearchCriteria();

            var filterResult = MeterInfoService.MeterInfos.Where(expr).Select(t => new MeterInfoModel
            {
                Id = t.Id,
                CustomerName=t.Customer!=null?t.Customer.Hu_ZXM:"",
                WayOfChargeName=t.WayOfCharge!=null?t.WayOfCharge.Shou_FFS:"",
                KindOfWaterUseName=t.KindOfWaterUse!=null?t.KindOfWaterUse.Yong_SXZ:"",
                MeterTypeName=t.MeterType!=null?t.MeterType.Yi_BLX:"",
                RelayTypeName=t.RelayType!=null?t.RelayType.Zhong_JLX:"",
                Zhong_JDZ=t.Zhong_JDZ,
                Zhong_JTD=t.Zhong_JTD,
                ConcentratorTypeName=t.ConcentratorType!=null?t.ConcentratorType.Ji_ZQLX:"",
                Ji_ZQDZ=t.Ji_ZQDZ,
                Ji_ZQTD=t.Ji_ZQTD,
                HandSetName=t.HandSetType!=null?t.HandSetType.Shou_CQLX:"",
                WaterCaliberName=t.WaterCaliber!=null?t.WaterCaliber.Shui_BKJ:"",
                Yi_BMC=t.Yi_BMC,
                Yi_BBH=t.Yi_BBH,
                Yi_BDZ=t.Yi_BDZ,
                Yi_BDD=t.Yi_BDD,
                Du_SBQ=t.Du_SBQ,
                Chao_BDTBC=t.Chao_BDTBC,
                Chao_BDTSC=t.Chao_BDTSC,
                Du_SSQ=t.Du_SSQ,
                Du_SBC=t.Du_SBC,
                OrderNo = t.OrderNo,


            }).OrderBy(t => t.OrderNo).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            sortId++.ToString(), 
                            c.Yi_BBH,
                            c.Yi_BDZ,
                            c.Du_SBQ.ToString(),
                            c.Chao_BDTBC.ToString(),
                            c.Du_SSQ.ToString(),
                            c.Chao_BDTSC.ToString(),
                            c.Du_SBC.ToString(),
                            c.Id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Create()
        {
            var model = new MeterInfoModel();
            InitModuleSet(model);
            InitMeterCode(model);
            return PartialView(model);
        }

        [HttpPost]
        [AdminOperateLog]
        public ActionResult Create(MeterInfoModel model)
        {
            if (ModelState.IsValid)
            {
                OperationResult result = MeterInfoService.Insert(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }
            }
            else
            {
                return PartialView(model);
            }
        }

        public ActionResult Edit(int Id)
        {
            var model = new MeterInfoModel();
            var entity = MeterInfoService.MeterInfos.FirstOrDefault(t => t.Id == Id);
            if (null != entity)
            {
                model = new MeterInfoModel
                {
                   Yong_HSZ_No=entity.Yong_HSZ_No,
                   Biao_CSZ_No=entity.Biao_CSZ_No,
                   Shou_FFS_No=entity.Shou_FFS_No,
                   Yong_SLX_No=entity.Yong_SLX_No,
                   Yi_BLX_No=entity.Yi_BLX_No,
                   Zhong_JLX_No=entity.Zhong_JLX_No,
                   Zhong_JDZ=entity.Zhong_JDZ,
                   Zhong_JTD=entity.Zhong_JTD,
                   Ji_ZQLX_No=entity.Ji_ZQLX_No,
                   Ji_ZQDZ=entity.Ji_ZQDZ,
                   Ji_ZQTD=entity.Ji_ZQTD,
                   Shou_CQLX_No=entity.Shou_CQLX_No,
                   Shui_BCS_No=entity.Shui_BCS_No,
                   Shui_BKJ_No=entity.Shui_BKJ_No,
                   Yi_BMC=entity.Yi_BMC,
                   Yi_BBH=entity.Yi_BBH,
                   Yi_BDZ=entity.Yi_BDZ,
                   Yi_BDD=entity.Yi_BDD,
                   Bei_L=entity.Bei_L,
                   Qian_FH=entity.Qian_FH,
                   An_ZWZ=entity.An_ZWZ,
                   Qi_YDT=entity.Qi_YRQ
                };
                InitModuleSet(model);
            }
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Edit(MeterInfoModel model)
        {
            if (ModelState.IsValid)
            {
                OperationResult result = MeterInfoService.Update(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }

            }
            else
            {
                return PartialView(model);
            }
        }


        public ActionResult Delete(int Id)
        {
            OperationResult result = MeterInfoService.Delete(Id);
            return Json(result);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public void Payment(int Id)
        {
            ReportDocument rd = new ReportDocument();
            string strReportName = "Payment.rpt";
            string strRptPath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Rpts//" + strReportName;
            rd.Load(strRptPath);
            var entity = MeterInfoService.MeterInfos.Where(t => t.Id == Id).Select(t => new MeterInfoModel { Du_SBQ = t.Du_SBQ });
           
            Fee fee = new Fee();
            foreach (var item in entity)
            {
             //   fee.Payment.AddPaymentRow("王理民", item.Du_SBQ.ToString(), item.Du_SBC.ToString());
            }
            rd.SetDataSource(fee);
            rd.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, false, "crReport");
        }

        private Expression<Func<MeterInfo, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<MeterInfo> bulider = new DynamicLambda<MeterInfo>();
            Expression<Func<MeterInfo, Boolean>> expr = null;
            if (!string.IsNullOrEmpty(Request["Yi_BBH"]))
            {
                var data = Request["Yi_BBH"].Trim();
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Yi_BBH.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Yi_BMC"]))
            {
                var data = Request["Yi_BMC"].Trim();
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Yi_BMC.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Zhong_JDZ"]))
            {
                var data = Request["Zhong_JDZ"].Trim();
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Zhong_JDZ.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Ji_ZQDZ"]))
            {
                var data = Request["Ji_ZQDZ"].Trim();
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Ji_ZQDZ.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Yong_SLX_No"]))
            {
                var data =  Convert.ToInt32(Request["Yong_SLX_No"]);
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Yong_SLX_No==data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Zhong_JLX_No"]))
            {
                var data = Convert.ToInt32(Request["Zhong_JLX_No"]);
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Zhong_JLX_No==data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Shou_CQLX_No"]))
            {
                var data = Convert.ToInt32(Request["Shou_CQLX_No"]);
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Shou_CQLX_No == data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Ji_ZQLX_No"]) && Request["Ji_ZQLX_No"] != "0")
            {
                var data = Convert.ToInt32(Request["Ji_ZQLX_No"]);
                Expression<Func<MeterInfo, Boolean>> tmp = t => (t.Ji_ZQLX_No == data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            Expression<Func<MeterInfo, Boolean>> tmpSolid = t => t.IsDeleted == false;
            expr = bulider.BuildQueryAnd(expr, tmpSolid);

            return expr;
        }

        private void  InitModuleSet(MeterInfoModel model)
        {
            //客户
            var Customers = CustomerService.Customers.Where(t => t.IsDeleted == false)
                .Select(t => new CustomerModel
                {
                    Id=t.Id,
                    Hu_ZXM=t.Hu_ZXM
                });
            foreach (var item in Customers)
            {
                model.CustomerItems.Add(new SelectListItem {Text=item.Hu_ZXM,Value=item.Id.ToString() });
            }
            //收费方式
            var WayOfChargeDatas=WayOfChargeService.WayOfCharges.Where(t=>t.IsDeleted==false)
                .Select(t=>new WayOfChargeModel{
                    Id=t.Id,
                    Shou_FFS=t.Shou_FFS
                });
            foreach (var item in WayOfChargeDatas)
            {
                model.WayOfChargeItems.Add(new SelectListItem {Text=item.Shou_FFS,Value=item.Id.ToString() });
            }
            //用水类型
            var KindOfWaterUseDatas = KindOfWaterUserService.KindOfWaterUses.Where(t => t.IsDeleted == false)
                .Select(t => new KindOfWaterUseModel
                {
                    Id = t.Id,
                    Yong_SXZ = t.Yong_SXZ
                });
            foreach (var item in KindOfWaterUseDatas)
            {
                model.KindOfWaterUseItems.Add(new SelectListItem { Text = item.Yong_SXZ, Value = item.Id.ToString() });
            }
            //仪表类型
            var MeterTypeDatas = MeterTypeService.MeterTypes.Where(t => t.IsDeleted == false)
                .Select(t=>new MeterTypeModel { 
                    Id=t.Id,
                    Yi_BLX=t.Yi_BLX
                });
            foreach (var item in MeterTypeDatas)
            {
                model.MeterTypeItems.Add(new SelectListItem {Text=item.Yi_BLX,Value=item.Id.ToString() });
            }
            //中继类型
            var RelayTypeDatas = RelayTypeService.RelayTypes.Where(t => t.IsDeleted == false)
                .Select(t => new RelayTypeModel
                {
                    Id = t.Id,
                    Zhong_JLX = t.Zhong_JLX
                });
            foreach (var item in RelayTypeDatas)
            {
                model.RelayTypeItems.Add(new SelectListItem { Text = item.Zhong_JLX, Value = item.Id.ToString() });
            }
            //集中器类型
            var ConcentratorTypeDatas = ConcentratorTypeService.ConcentratorTypes.Where(t => t.IsDeleted == false)
                .Select(t => new ConcentratorTypeModel
                {
                    Id = t.Id,
                    Ji_ZQLX = t.Ji_ZQLX
                });
            foreach (var item in ConcentratorTypeDatas)
            {
                model.ConcentratorTypeItems.Add(new SelectListItem { Text = item.Ji_ZQLX, Value = item.Id.ToString() });
            }
            //手抄器类型
            var HandSetDatas = HandSetTypeService.HandSetTypes.Where(t => t.IsDeleted == false)
                .Select(t => new HandSetTypeModel
                {
                    Id = t.Id,
                    Shou_CQLX = t.Shou_CQLX
                });
            foreach (var item in HandSetDatas)
            {
                model.HandSetItems.Add(new SelectListItem { Text = item.Shou_CQLX, Value = item.Id.ToString() });
            }
            //水表口径
            var WatercaliberDatas = WaterCaliberService.WaterCalibers.Where(t => t.IsDeleted == false)
                .Select(t => new WaterCaliberModel { 
                    Id=t.Id,
                    Shui_BKJ=t.Shui_BKJ
                });
            foreach (var item in WatercaliberDatas)
            {
                model.WaterCaliberItems.Add(new SelectListItem {Text=item.Shui_BKJ,Value=item.Id.ToString() });
            }
            //水表厂商
            var ManufacturerDatas = ManufacturerService.Manufacturers.Where(t => t.IsDeleted == false)
                .Select(t => new ManufacturerModel { 
                    Id=t.Id,
                    Shui_BCS=t.Shui_BCS
                });
            foreach (var item in ManufacturerDatas)
            {
                model.ManufacturerItems.Add(new SelectListItem {Text=item.Shui_BCS,Value=item.Id.ToString() });
            }
            //表册
            var MeterBooks = MeterBookService.MeterBooks.Where(t => t.IsDeleted == false)
                .Select(t => new MeterBookModel {
                    id=t.Id,
                    Biao_CMC=t.Biao_CMC
                });
            foreach (var item in MeterBooks)
            {
                model.MeterBookItems.Add(new SelectListItem {Text=item.Biao_CMC,Value=item.id.ToString() });
            }
        }

        private void InitMeterCode(MeterInfoModel model)
        {
            var codeRule = RuleOfCodeService.RuleOfCodes.FirstOrDefault(t => t.Bian_MDX == 2);
            if (codeRule != null)
            {
                model.RuleOfCode = codeRule.Bian_MGZDY;
            }
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
        public JsonResult IsUnique_Available(string Yi_BBH)
        {
            if (!string.IsNullOrEmpty(Yi_BBH))
            {
                var entity = MeterInfoService.MeterInfos.FirstOrDefault(t => t.Yi_BBH == Yi_BBH);
         
                if (entity != null)
                {
                    //string message = "该用户编号已经存在";
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }

    }
}

